#!/bin/bash

# 自定义action函数，实现通用action功能
if_success() {
  echo -en "\033[60G[\033[1;32m  OK  \033[0;39m]\r"
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$Log_Dir/restart.log"
  return 0
}

failure() {
  local rc=$?
  local message="$1"
  echo -en "\033[60G[\033[1;31mFAILED\033[0;39m]\r"
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $message" >> "$Log_Dir/restart.log"
  [ -x /Daili/plymouth ] && /Daili/plymouth --details
  return $rc
}

action() {
  local STRING rc

  STRING=$1
  echo -n "$STRING "
  shift
  "$@" && success "$STRING" || failure "$STRING"
  rc=$?
  echo
  return $rc
}

# 定义路径变量
Server_Dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
Conf_Dir="$Server_Dir/conf"
Log_Dir="$Server_Dir/logs"

# 确保日志文件存在
mkdir -p "$Log_Dir"
touch "$Log_Dir/restart.log"

# 记录启动脚本的日志信息
echo "[$(date '+%Y-%m-%d %H:%M:%S')] 启动脚本开始执行" >> "$Log_Dir/restart.log"

# 查询并关闭程序进程
PID=$(ps -ef | grep [c]lash-linux-a | awk '{print $2}')
if [ -n "$PID" ]; then
  echo "准备重启clash"
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] 准备重启clash，PID: $PID" >> "$Log_Dir/restart.log"
  kill -9 "$PID"
else
  echo "未找到clash进程，准备启动"
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] 未找到clash进程，准备启动" >> "$Log_Dir/restart.log"
fi

sleep 1

# 获取CPU架构
CpuArch=$(arch 2>/dev/null || uname -m 2>/dev/null)
if [ -z "$CpuArch" ]; then
  echo -e "\033[31m\n[ERROR] 获取CPU架构失败！\033[0m"
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] 获取CPU架构失败！" >> "$Log_Dir/restart.log"
  exit 1
fi

# 记录CPU架构信息
echo "[$(date '+%Y-%m-%d %H:%M:%S')] 检测到的CPU架构: $CpuArch" >> "$Log_Dir/restart.log"

# 启动clash服务
Text5="服务启动成功！"
Text6="服务启动失败！"

case $CpuArch in
  x86_64)
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] 启动clash-linux-amd64" >> "$Log_Dir/restart.log"
    nohup "$Server_Dir/Daili/clash-linux-amd64" -d "$Conf_Dir" &> "$Log_Dir/clash.log" &
    ;;
  aarch64|arm64)
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] 启动clash-linux-arm64" >> "$Log_Dir/restart.log"
    nohup "$Server_Dir/Daili/clash-linux-arm64" -d "$Conf_Dir" &> "$Log_Dir/clash.log" &
    ;;
  armv7)
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] 启动clash-linux-armv7" >> "$Log_Dir/restart.log"
    nohup "$Server_Dir/Daili/clash-linux-armv7" -d "$Conf_Dir" &> "$Log_Dir/clash.log" &
    ;;
  *)
    echo -e "\033[31m\n[ERROR] 不支持的CPU架构！\033[0m"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] 不支持的CPU架构: $CpuArch" >> "$Log_Dir/restart.log"
    exit 1
    ;;
esac

sleep 2  # 等待一段时间以确保服务启动

# 捕获nohup命令的返回状态
nohup_pid=$!
if ! wait $nohup_pid; then
  # 获取nohup命令的输出信息
  nohup_output=$(tail -n 1 "$Log_Dir/clash.log")
  if_success "$Text5" "$Text6 $nohup_output"
else
  # 检查服务是否成功启动
  if netstat -tuln | grep -E '9090|7890' &> /dev/null; then
    if_success "$Text5" "$Text6"
  else
    if_success "$Text5" "$Text6"
  fi
fi
